package com.winhxd.b2c.common.context.version;

import com.winhxd.b2c.common.context.hystrix.ContextCallableWrapper;

import java.util.concurrent.Callable;

/**
 * 微服务版本控制
 *
 * @author lixiaodong
 */
public class VersionContext {
    public static final String HEADER_NAME = "msVer";

    private static ThreadLocal<String> currentVersion = new ThreadLocal<>();

    public static String getCurrentVersion() {
        return currentVersion.get();
    }

    public static void setCurrentVersion(String ver) {
        currentVersion.set(ver);
    }

    public static void clean() {
        currentVersion.remove();
    }

    public static class VersionContextCallableWrapper implements ContextCallableWrapper {
        private static class HystrixCallback<V> implements Callable<V> {
            private Callable<V> delegate;
            private String version;

            public HystrixCallback(Callable<V> delegate, String version) {
                this.delegate = delegate;
                this.version = version;
            }

            @Override
            public V call() throws Exception {
                try {
                    currentVersion.set(this.version);
                    return this.delegate.call();
                } finally {
                    currentVersion.remove();
                }
            }
        }

        @Override
        public <V> Callable<V> wrap(Callable<V> callable) {
            return new VersionContextCallableWrapper.HystrixCallback<>(callable, currentVersion.get());
        }
    }
}
